package com.bookstore.service;//package com.bookstore.service;

import com.bookstore.entity.Book;
import com.bookstore.entity.Category;
import com.bookstore.entity.Comments;
import com.bookstore.entity.User;
import com.bookstore.mapper.BookMapper;
import com.bookstore.mapper.CommentsMapper;
import com.bookstore.mapper.RecommendedMapper;
import com.bookstore.mapper.UserMapper;
import com.bookstore.mapper.RecommendedMapper;
import com.bookstore.mapper.UserMapper;
import com.bookstore.utils.CFUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BookService {
    @Autowired
    BookMapper bookMapper;
    @Autowired
    CommentsMapper commentsMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    RecommendedMapper recommendedMapper;
    /**
     * 查找书籍并且分页
     */
    public PageInfo<Book> getBookByPage(int pageNum, int pageSize) {
        //分页处理，显示第一页的10条数据
        PageHelper.startPage(pageNum, pageSize);
        List<Book> bookList = bookMapper.getBookByPage((pageNum-1)*pageSize, pageSize*pageNum);
        Category category = bookList.get(0).getCategory();
        System.out.println(category.getcName());
        // 取分页信息
        PageInfo pageInfo = new PageInfo<>();
        //总的记录数
        Integer total = bookMapper.countSize();
        Integer number = total/pageSize;
        number += total%pageSize>0?1:0;
        pageInfo.setTotal(total);
        pageInfo.setPages(number);
        pageInfo.setList(bookList);
        return pageInfo;
    }

    public List<Book> getBookTop(){
       List<Book> books = bookMapper.getBookTop();
       if (books.size()>0){
           return books;
       }else{
           return null;
       }
    }


    @Transactional(isolation = Isolation.READ_COMMITTED)
    public synchronized int insertBook(Book book){
        int insert=bookMapper.insert(book);
        return insert;
    }

    @Transactional(isolation = Isolation.READ_COMMITTED)
    public synchronized int insertSelective(Book book){
        int insert=bookMapper.insert(book);
        return insert;
    }

    /**
     * 通过修改评论次数和评论总分来修改平均分,同时完成评论
     * @return
     */
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public synchronized int updateBookScore(Comments comments){
            Book book = bookMapper.getBookNumber(comments.getBookId());
        Double totalNumber = book.getTotalScore();
        if (totalNumber==-1){
            totalNumber+=comments.getScore()+1;
        }else{
            totalNumber+=comments.getScore();
        }
        Long scoreNumber = book.getScoreNumber();
        if (scoreNumber==-1){
            scoreNumber+=2;
        }else {
            scoreNumber+=1;
        }
        Double bookScore = (totalNumber/scoreNumber);
        int insert = commentsMapper.insertSelective(comments);
        int update = bookMapper.updateBookNumber(scoreNumber,totalNumber,bookScore);
        if (insert>0 && update>0){
            return 1;
        }else{
            return 0;
        }
    }

    /**
     * 删除图书
     */
    @Transactional
    public int delBook(String bookID){
        int del = bookMapper.delBook(bookID);
        int delComments = commentsMapper.delCommentsByBookId(bookID);
        if (delComments>0 && del>0){
            return del;
        }else{
            return 0;
        }

    }

    /**
     * 根据参数更新数据
     */
    public int updateBook(Book book){
        int update = bookMapper.updateBook(book);
        return update;
}

    /**
     * 更具参数类型来查找图书
     */
    public PageInfo<Book> getBookByType( int pageNum, int pageSize, Integer typeID){
        //分页处理，显示第一页的10条数据
        PageHelper.startPage(pageNum, pageSize);
        List<Book> bookList = bookMapper.getBookByType((pageNum-1)*pageSize, pageSize*pageNum,typeID);
        // 取分页信息
        PageInfo pageInfo = new PageInfo();
        int count = bookMapper.countSize(typeID);
        pageInfo.setTotal(count);
        pageInfo.setList(bookList);
        return pageInfo;
    }

   public PageInfo<Book> getBookByName(String bookName,int pageNum, int pageSize){
       //分页处理，显示第一页的10条数据
       PageHelper.startPage(pageNum, pageSize);
       List<Book> bookList = bookMapper.getBookByName(bookName,(pageNum-1)*pageSize, pageSize*pageNum);
       // 取分页信息
       PageInfo pageInfo = new PageInfo<Book>(bookList);
       pageInfo.setTotal(bookMapper.getBookByNameNumber(bookName));
       pageInfo.setList(bookList);
       System.out.println(pageInfo.toString());
       return pageInfo;
   }

    /**
     * 根据图书的类查询图书
     * @param pageNum
     * @param pageSize
     * @param cId
     * @return
     */
   public PageInfo<Book> getBookByCategory(int pageNum, int pageSize, Long cId){
        PageHelper.startPage(pageNum,pageSize);
        List<Book> bookList = bookMapper.getBookByCategory(cId);
        PageInfo<Book>  pageInfo = new PageInfo<Book>(bookList);
        return pageInfo;
   }

    /**
     * 根据一级分类查询图书
     * @param pageNum
     * @param pageSize
     * @param cId
     * @return
     */
    public PageInfo<Book> getBookByParentCategory(int pageNum, int pageSize, Long cId){
        PageHelper.startPage(pageNum,pageSize);
        List<Book> bookList = bookMapper.getBookByParentCategory(cId);
        PageInfo<Book>  pageInfo = new PageInfo<Book>(bookList);
        return pageInfo;
    }

    /**
     * 根据排序字段获取前十条记录
     * @param fliedName
     * @return
     */
    public List<Book> getTop10BookByFliedName(String fliedName){
        List<Book> bookList = null;
        if (fliedName.equals("SCORE")){//根据评分排序
            bookList = bookMapper.getBookOrderByScore();
        }
        if (fliedName.equals("UPLOAD_DATE")){//根据上传时间排序
            bookList = bookMapper.getBookOrderByUpLoadDate();
        }
        if (fliedName.equals("DOWNLOAD_NUMBER")){//根据下载量排序
            bookList = bookMapper.getBookOrderByDownloadNumber();
        }
        return bookList;
    }

    /**
     * 根据图书id查询图书
     * @param bid
     * @return
     */
    public Book getBookById(String bid){
        Book book = bookMapper.getBookById(bid);
        return book;
    }

    /**
     * 根据协同算法推荐图书
     * @param simUser
     * @return
     */
    public PageInfo<Book> getBookByCf(Long simUser){
       Integer size= commentsMapper.userCount();
       if (size<1){
           System.out.println("推荐前10本书籍给用户");
           List<Book> books = bookMapper.getBookTop();
           System.out.println("1"+books.size());
           PageHelper.startPage(1, 10);
           PageInfo pageInfo = new PageInfo<>();
           pageInfo.setTotal(10);
           pageInfo.setPrePage(1);
           pageInfo.setEndRow(0);
           pageInfo.setList(books);
           return pageInfo;
       }else {
           System.out.println("根据协同算法获取推荐书籍");
           List<User> users = userMapper.getUserId();

           Map<Long, Map<String, Double>> mapMap = new HashMap<>();
           for (User user : users) {
               Map<String, Double> pref = new HashMap<>();
               List<Comments> list = commentsMapper.getComments(user.getuId());
               for (Comments comments : list) {
                   System.out.println(comments.getBookId()+"/t"+ comments.getScore());
                   pref.put(comments.getBookId(), comments.getScore());
               }
               List<Book> books = bookMapper.getBookIds(user.getuId());
               for (Book book : books) {
                   pref.put(book.getBookId(), 0.0);
               }
               mapMap.put(user.getuId(), pref);
           }
           Long user = CFUtils.getUser(mapMap, simUser);
           if (user == null){
               List<Book> books = bookMapper.getBookTop();
               System.out.println("2"+books.size());
               //分页处理，显示第一页的10条数据
               PageHelper.startPage(0, 10);
               PageInfo pageInfo = new PageInfo<>();
               pageInfo.setTotal(10);
               pageInfo.setPrePage(1);
               pageInfo.setList(books);
               return pageInfo;
           }
           List<Book> books = bookMapper.getMaxCommentsBook(user);
           if (books.size()<1){
               List<Book> book = bookMapper.getBookTop();
               System.out.println("1:"+book.size());
               //分页处理，显示第一页的10条数据
               PageHelper.startPage(0, 10);
               PageInfo pageInfo = new PageInfo<>();
               pageInfo.setTotal(10);
               pageInfo.setPrePage(1);
               pageInfo.setIsFirstPage(true);
               pageInfo.setList(book);
               return pageInfo;
           }else{
               //分页处理，显示第一页的10条数据
               PageHelper.startPage(0, 10);
               PageInfo pageInfo = new PageInfo<>();
               pageInfo.setTotal(10);
               pageInfo.setPrePage(1);
               pageInfo.setList(books);
               return pageInfo;
           }

       }
   }

   public Book getModifyMessage(String bookId){
        Book book = bookMapper.getModifyMessage(bookId);
        if (book!=null){
            return book;
        }else{
            return null;
        }
    }

    /**
     * 更新图书的评分
     * @param bookId
     * @param score
     */
    @Transactional
    public void countScore(String bookId,short score){
        try {
            Book book = bookMapper.getBookById(bookId);
            int total_score =(int) book.getTotalScore()+score;
            int scoreNumber = (int)(book.getScoreNumber()+1);
            double score2 = (double) (total_score/ scoreNumber);
            book.setTotalScore(total_score);
            book.setScoreNumber(new Long(scoreNumber));
            book.setScore(score2);
            bookMapper.updateBook(book);
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
